<template>
  <div class="ReportTemplateMaintain item2">

    <section class="layer">
      <div class="box">
        <div class="box-header">
          <span class="box-title">查询条件</span>
        </div>
        <div class="box-body">
          <el-form ref="searchForm" :model="searchForm" label-width="60px">
            <el-row :gutter="12">
              <el-col :md="12" :lg="8" :xl="6">
                <el-form-item label="数据源名称" prop="datasourceName" label-width="90px">
                  <el-input v-model="searchForm.datasourceName" clearable placeholder="请输入" style="width:100%;"/>
                </el-form-item>
              </el-col>
              <el-col :md="12" :lg="8" :xl="6">
                <el-form-item label="主机地址" prop="datasourceUrl" label-width="90px">
                  <el-input v-model="searchForm.datasourceUrl" clearable placeholder="请输入" style="width:100%;"/>
                </el-form-item>
              </el-col>
              <el-col :md="12" :lg="8" :xl="6">
                <el-button @click="resetForm">重置</el-button>
                <el-button type="primary" @click="search">查询</el-button>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </div>
    </section>
    <section class="layer">
      <div class="box">
        <div class="box-header handle">
          <span class="box-title">数据源列表</span>
          <div class="box-tools">
            <el-button type="success" @click="addNewList">新增</el-button>
          </div>
        </div>
        <div class="box-body">
          <el-table v-loading="loading" :data="tableData" element-loading-spinner="el-loading1" height="stying" border style="width: 100%">
            <el-table-column type="index" width="60" label="序号" align="center"/>
            <el-table-column :show-overflow-tooltip="true" prop="datasourceName" label="数据源名称" min-width="200" align="center" />
            <el-table-column :show-overflow-tooltip="true" prop="datasourceTypeName" label="数据源类型" min-width="200" align="center" />
            <el-table-column :show-overflow-tooltip="true" prop="datasourceDesc" label="描述" min-width="220" align="center" />
            <el-table-column prop="" label="配置内容" min-width="480" align="left">
              <template slot-scope="scope">
                <div v-if="scope.row.datasourceTypeName==='JSON'">
                  <div><span style="color: #1B65B9">JSON URL：</span>{{ scope.row.datasourceUrl }}</div>
                  <div><span style="color: #1B65B9">selectExpression：</span>{{ scope.row.selectExpression }}</div>
                </div>
                <div v-else>
                  <div><span style="color: #1B65B9">连接URL：</span>{{ scope.row.datasourceUrl }}</div>
                  <div><span style="color: #1B65B9">用户名：</span>{{ scope.row.username }}</div>
                </div>
              </template>
            </el-table-column>
            <el-table-column :show-overflow-tooltip="true" prop="updtTime" label="最后修改日期" min-width="180" align="center">
              <template slot-scope="scope">
                <span>{{ $dateFormat( scope.row.updtTime) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="140" fixed="right" align="center">
              <template slot-scope="scope">
                <el-button v-no-more-click class="modify" type="text" @click.stop="checkRow(scope.row)">测试
                </el-button><el-button v-no-more-click style="color: #67c23a" class="modify" type="text" @click.stop="modifyrow(scope.row)">修改
                </el-button><el-button v-no-more-click class="delete" type="text" @click.stop="deleteRow(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            :current-page="currentPage"
            :page-sizes="[15, 30, 50, 100]"
            :page-size="pageSize"
            :total="total"
            small
            layout="slot, sizes, prev, pager, next, jumper"
            @current-change="handleCurrentChange"
            @size-change="handleSizeChange">
            <template slot>
              <span class="el-pagination__total">{{ `总共${total}条 显示${startRow}-${endRow}条` }}</span>
            </template>
          </el-pagination>
        </div>
      </div>
    </section>
    <el-dialog v-dialogDrag :title="dialogObj.title" :visible.sync="dialogObj.isShow" :close-on-click-modal="false" width="50%" destroy-on-close @close="dialogcel">
      <el-form ref="form" :model="form" :rules="rules" label-width="130px">
        <el-form-item label="数据源类型" prop="datasourceType">
          <el-select v-model="datasourceTypeName" :disabled="!isadd" clearable placeholder="请选择" style="width:100%;" @change="changedatasourceType" >
            <el-option v-for="(item, index) in modelTypeList" :key="index" :label="item.category" :value="index"/>
          </el-select>
        </el-form-item>
        <el-form-item label="名称" prop="datasourceName">
          <el-input v-model="form.datasourceName" clearable placeholder="请输入"/>
        </el-form-item>
        <el-form-item v-if="form.datasourceType!==2" label="连接URL" prop="datasourceUrl">
          <el-input v-model="form.datasourceUrl" clearable placeholder="请输入"/>
        </el-form-item>
        <el-form-item v-if="form.datasourceType!==2" label="用户名" prop="username">
          <el-input v-model="form.username" clearable placeholder="请输入"/>
        </el-form-item>
        <el-form-item v-if="form.datasourceType!==2" label="密码" prop="password">
          <el-input v-model="form.password" clearable placeholder="请输入"/>
        </el-form-item>
        <el-form-item v-if="form.datasourceType===2" label="JSON URL" prop="datasourceUrl">
          <el-input v-model="form.datasourceUrl" clearable placeholder="请输入"/>
        </el-form-item>
        <el-form-item v-if="form.datasourceType===2" label="selectExpression" prop="selectExpression">
          <el-input v-model="form.selectExpression" clearable placeholder="请输入"/>
        </el-form-item>
        <el-form-item label="描述" prop="datasourceDesc">
          <el-input v-model="form.datasourceDesc" :rows="2" type="textarea" clearable placeholder="请输入" maxlength="50" show-word-limit/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-no-more-click type="primary" @click="checkRowform">测试</el-button>
        <el-button @click="dialogObj.isShow = false" >关闭</el-button><el-button type="primary" @click="confirmForm(isadd)">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { datasourceGetAllPage, datasourceAdd, datasourceUpdate, datasourceDelete, datasourceConfigTest } from '@/api/data-source-management'
import { jsonx } from '@/utils/data'
export default {
  name: 'ReportTemplateMaintain',
  components: {
  },
  mixins: [

  ],
  props: {

  },
  data() {
    return {
      testPass: true,
      searchForm: {
        datasourceName: '',
        datasourceUrl: ''
      },
      tableData: [],
      loading: false,
      modelTypeList: [], // 数据源类型
      reportID: '',
      dialogObj: {
        isShow: false,
        title: '添加数据源',
        rows: []
      },
      rules: {
        datasourceType: [{ required: true, message: '请选择数据源类型', trigger: 'change' }],
        datasourceName: [{ required: true, message: '请输入名称', trigger: 'blur' }],
        datasourceUrl: [{ required: true, message: '请输入url', trigger: 'blur' }],
        username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
        selectExpression: [{ required: true, message: '请输入selectExpression', trigger: 'blur' }]
      },
      form: {
        datasourceType: '',
        datasourceName: '',
        datasourceUrl: '',
        username: '',
        datasourceDesc: '',
        password: '',
        selectExpression: ''
      },
      datasourceTypeName: 'MySQL57',
      // 总条数
      total: 0,
      startRow: 0,
      endRow: 0,
      // 每页多少条
      pageSize: 15,
      // 当前页
      currentPage: 1,
      isadd: false
    }
  },
  computed: {

  },
  watch: {

  },
  created() {
    this.getListFactorDefine()
  },
  mounted() {
    this.modelTypeList = jsonx.data
    this.form.datasourceType = '0'
  },
  methods: {
    // 查询
    search() {
      this.currentPage = 1
      this.getListFactorDefine()
    },
    // 新增
    addNewList() {
      this.isadd = true
      this.dialogObj.isShow = true
      this.dialogObj.title = '新增数据源'
    },
    modifyrow(row) {
      this.isadd = false
      this.dialogObj.isShow = true
      this.dialogObj.title = '修改数据源'
      this.form = Object.assign({}, row)
    },
    // 重置
    resetForm() {
      this.$refs.searchForm.resetFields()
      this.search()
    },
    dialogcel() {
      this.$refs['form'].resetFields()
      // this.form.datasourceType = ''
      this.form.datasourceName = ''
      this.form.datasourceUrl = ''
      // this.form.datasourceStatus = ''
      this.form.username = ''
      this.form.datasourceDesc = ''
      this.form.password = ''
    },
    // 删除
    deleteRow(row) {
      this.$confirm(`<div class="myalert-header">操作提醒</div><div class="myalert-content">您进行的是删除操作, 是否继续?</div></div>`, {
        confirmButtonText: '确定',
        dangerouslyUseHTMLString: true,
        cancelButtonText: '取消',
        type: 'warning'
      }).then(_ => {
        datasourceDelete(row.datasourceId).then(res => {
          if (res.data.code === 0) {
            this.$message({
              type: 'success',
              dangerouslyUseHTMLString: true,
              message: `<strong>操作成功</strong><p>${res.data.message}</p>`
            })
            this.getListFactorDefine()
          } else {
            this.$alert(`<div class="myalert-header">操作失败</div><div class="myalert-content">${res.data.message}</div></div>`, {
              confirmButtonText: '确定',
              dangerouslyUseHTMLString: true,
              type: 'error'
            })
          }
        }).catch(err => {
          console.log(err)
        })
      }).catch(_ => {})
    },
    confirmForm() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.isadd) {
            let params = {
              ...this.form,
              userId: ''
            }
            datasourceAdd(params).then(res => {
              if (res.data.code === 0) {
                this.$message({
                  type: 'success',
                  dangerouslyUseHTMLString: true,
                  message: `<strong>操作成功</strong><p>${res.data.message}</p>`
                })
                this.currentPage = 1
                this.dialogObj.isShow = false
                this.testPass = true
                this.getListFactorDefine()
              } else {
                this.$alert(`<div class="myalert-header">操作失败</div><div class="myalert-content">${res.data.message}</div></div>`, {
                  confirmButtonText: '确定',
                  dangerouslyUseHTMLString: true,
                  type: 'error'
                })
                // this.loading = false
              }
            }).catch(err => {
              this.dialog = false
              console.log(err)
            })
          } else {
            let params = {
              ...this.form,
              userId: ''
            }
            datasourceUpdate(params).then(res => {
              if (res.data.code === 0) {
                this.$message({
                  type: 'success',
                  dangerouslyUseHTMLString: true,
                  message: `<strong>操作成功</strong><p>${res.data.message}</p>`
                })
                this.dialogObj.isShow = false
                this.testPass = true
                this.getListFactorDefine()
              } else {
                this.$alert(`<div class="myalert-header">操作失败</div><div class="myalert-content">${res.data.message}</div></div>`, {
                  confirmButtonText: '确定',
                  dangerouslyUseHTMLString: true,
                  type: 'error'
                })
                // this.loading = false
              }
            }).catch(err => {
              console.log(err)
            })
          }
        }
      })
    },
    // 分页查询
    getListFactorDefine() {
      let params = {
        pageNo: this.currentPage,
        pageSize: this.pageSize,
        ...this.searchForm
      }
      this.loading = true
      datasourceGetAllPage(params).then(res => {
        if (res.data.code === 0) {
          this.tableData = res.data.data
          this.total = res.data.data.length
          const num1 = this.pageSize * (this.currentPage - 1) + 1
          const num2 = this.pageSize * this.currentPage > this.total ? this.total : this.pageSize * this.currentPage
          this.startRow = num1
          this.endRow = num2
          this.loading = false
        } else {
          this.$alert(res.data.message, {
            type: 'error',
            confirmButtonText: '确定'
          })
          this.loading = false
        }
      })
    },
    // 分页器
    handleSizeChange(val) {
      this.pageSize = val
      this.getListFactorDefine()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.getListFactorDefine()
    },
    checkRowform() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          let params = {
            ...this.form
          }
          datasourceConfigTest(params).then(res => {
            if (res.data.code === 0) {
              this.$message({
                type: 'success',
                dangerouslyUseHTMLString: true,
                message: `<strong>操作成功</strong><p>${res.data.message}</p>`
              })
              this.testPass = false
            } else {
              this.$alert(`<div class="myalert-header">操作失败</div><div class="myalert-content">${res.data.message}</div></div>`, {
                confirmButtonText: '确定',
                dangerouslyUseHTMLString: true,
                type: 'error'
              })
              // this.loading = false
            }
          }).catch(err => {
            console.log(err)
          })
        }
      })
    },
    // 测试
    checkRow(row) {
      datasourceConfigTest(row).then(res => {
        if (res.data.code === 0) {
          this.$message({
            type: 'success',
            dangerouslyUseHTMLString: true,
            message: `<strong>操作成功</strong><p>${res.data.message}</p>`
          })
          // this.dialogObj.isShow = false
          // this.getListFactorDefine()
        } else {
          this.$alert(`<div class="myalert-header">操作失败</div><div class="myalert-content">${res.data.message}</div></div>`, {
            confirmButtonText: '确定',
            dangerouslyUseHTMLString: true,
            type: 'error'
          })
          // this.loading = false
        }
      }).catch(err => {
        console.log(err)
      })
    },
    // 修改datasource
    changedatasourceType(val) {
      this.form.datasourceType = val
    }
  }
}
</script>

<style scoped lang="scss">
  .ReportTemplateMaintain {
    height: 100%;

    section:last-child {
      height: calc(100% - 108px);

      .el-row {
        height: 100%;

        .el-col {
          height: 100%;

          .box {
            height: 100%;

            .box-body {
              height: calc(100% - 40px);
            }
          }
        }
      }
    }
  }
</style>
